package com.changgou.filter;


import com.changgou.util.JwtUtil;
import com.netflix.client.http.HttpResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName: userFilter
 * @Author: ZWJ
 * @Date: 2020-09-02 21:09
 * @Synopsis: Null
 **/
@Component
public class userFilter implements Ordered, GlobalFilter {
    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
      
        //获取请求路径
        String path = request.getURI().getPath();

        if (path.contains("/api/user/login")) {
            //判断当访问登录操作时,进行放行
            return chain.filter(exchange);
        }
        //请求头
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);

        if (token == null) {
            //从请求头没有令牌
            //从请求参数查找令牌
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
            if (token == null) {
                HttpCookie first = request.getCookies().getFirst(AUTHORIZE_TOKEN);
                if (first==null){
                    //请求参数中没有令牌
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                token=first.getValue();
                request.mutate().header(AUTHORIZE_TOKEN,"Bearer "+token);
            }

        }

       /* //拿到了令牌
        try {
            //进行解析
            Claims claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }*/

        //解析成功放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
